import cv2
import numpy as np

# 假设我们有一个包含圆形和矩形的图像
image2 = cv2.imread('../img/zTZR7rYaQj.jpg', cv2.IMREAD_GRAYSCALE)

# 二值化图像
#_, thresh = cv2.threshold(image2, 127, 255, cv2.THRESH_BINARY_INV)

# 查找轮廓
contours, _ = cv2.findContours(image2, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# 创建一个空白图像来绘制轮廓和标记区域
output = np.zeros_like(image2)

# 区域计数器
region_count = 0

# 遍历所有轮廓
for contour in contours:
    # 绘制轮廓
    cv2.drawContours(output, [contour], -1, (255), 1)

    # 计算轮廓的边界框
    x, y, w, h = cv2.boundingRect(contour)

    # 检查边界框是否在图像范围内
    if x >= 0 and y >= 0 and x + w <= image2.shape[1] and y + h <= image2.shape[0]:
        # 在边界框的左上角标记区域编号
        cv2.putText(output, str(region_count + 1), (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1, (255), 2)
        region_count += 1

# 显示结果
cv2.imshow('Region Counting', output)
cv2.waitKey(0)
cv2.destroyAllWindows()

# 打印区域数量
print(f'Number of regions: {region_count}')